import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Job, JobStatus } from './entities/job.entity';
import { CreateJobDto } from './dto/create-job.dto';
import { UpdateJobDto } from './dto/update-job.dto';

@Injectable()
export class JobsService {
  constructor(
    @InjectRepository(Job)
    private readonly jobRepository: Repository<Job>,
  ) {}

  async create(createJobDto: CreateJobDto): Promise<Job> {
    // 确保budget字段被正确处理
    const now = new Date();
    const jobData = {
      ...createJobDto,
      deadline: new Date(createJobDto.deadline),
      budget: createJobDto.budget || {},
      updatedAt: now
    };
    
    const job = this.jobRepository.create(jobData);
    return await this.jobRepository.save(job);
  }

  async findAll(): Promise<Job[]> {
    return await this.jobRepository.find({
      order: { createdAt: 'DESC' },
    });
  }

  async findOne(id: string): Promise<Job> {
    return await this.jobRepository.findOne({ where: { id } });
  }

  async update(id: string, updateJobDto: UpdateJobDto): Promise<Job> {
    const job = await this.findOne(id);
    if (!job) {
      throw new Error('Job not found');
    }

    const updateData: any = { ...updateJobDto };
    if (updateJobDto.deadline) {
      updateData.deadline = new Date(updateJobDto.deadline);
    }

    await this.jobRepository.update(id, updateData);
    return await this.findOne(id);
  }

  async remove(id: string): Promise<void> {
    const result = await this.jobRepository.delete(id);
    if (result.affected === 0) {
      throw new Error('Job not found');
    }
  }

  async findByStatus(status: JobStatus): Promise<Job[]> {
    return await this.jobRepository.find({
      where: { status },
      order: { createdAt: 'DESC' },
    });
  }

  async findByCategory(category: string): Promise<Job[]> {
    return await this.jobRepository.find({
      where: { category },
      order: { createdAt: 'DESC' },
    });
  }

  async findByWalletAddress(walletAddress: string): Promise<Job[]> {
    return await this.jobRepository.find({
      where: { walletAddress },
      order: { createdAt: 'DESC' },
    });
  }
} 